var cart = document.getElementById("cart");
var list = document.querySelector('#cart .list');
var emptyCart = document.querySelector('.empty-cart');
var totalSpan = document.getElementById('total');
var all = document.getElementsByName("all")[0];

// 初始化购物车
function initCart() {
    updateCartStatus();
}

// 更新购物车状态（是否显示空购物车提示）
function updateCartStatus() {
    if (list.children.length === 0) {
        emptyCart.style.display = 'block';
    } else {
        emptyCart.style.display = 'none';
    }
}

// 添加商品到购物车
function addToCart(productInfo) {
    const productHTML = `
        <div class="product clear">
            <div class="check fl">
                <input type="checkbox" class="checkbox" name="check">
            </div>
            <div class="info fl">
                <img src="${productInfo.imgSrc}">
                <p>${productInfo.name}</p>
            </div>
            <div class="pic fl">${productInfo.price}</div>
            <div class="num fl">
                <span class="jian">-</span>
                <input type="text" name="num" value="${productInfo.quantity}">
                <span class="add">+</span>
            </div>
            <div class="rmb fl">${(productInfo.price * productInfo.quantity).toFixed(2)}</div>
            <div class="handle fl">
                <a href="javascript:;" class="delete">删除</a>
            </div>
        </div>
    `;
    list.insertAdjacentHTML('beforeend', productHTML);
    bindCartEvents();
    total();
}

// 将 addToCart 挂载到 window 对象上
window.addToCart = addToCart;

// 绑定购物车事件
function bindCartEvents() {
    // 绑定数量调整按钮事件
    const addBtns = document.querySelectorAll('.add');
    const jianBtns = document.querySelectorAll('.jian');
    const numInputs = document.querySelectorAll('input[name="num"]');

    addBtns.forEach((btn, index) => {
        btn.addEventListener('click', function() {
            const input = numInputs[index];
            let value = parseInt(input.value);
            input.value = value + 1;
            updateProductTotal(index);
        });
    });

    jianBtns.forEach((btn, index) => {
        btn.addEventListener('click', function() {
            const input = numInputs[index];
            let value = parseInt(input.value);
            if (value > 1) {
                input.value = value - 1;
                updateProductTotal(index);
            }
        });
    });

    // 绑定删除按钮事件
    const deleteBtns = document.querySelectorAll('.delete');
    deleteBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const product = this.closest('.product');
            product.remove();
            updateCartStatus();
            total();
        });
    });

    // 绑定全选复选框事件
    all.addEventListener('change', function() {
        const checkboxes = document.querySelectorAll('.checkbox');
        checkboxes.forEach(checkbox => {
            checkbox.checked = this.checked;
        });
        total();
    });

    // 绑定商品复选框事件
    const checkboxes = document.querySelectorAll('.checkbox');
    checkboxes.forEach(checkbox => {
        checkbox.addEventListener('change', total);
    });
}

// 更新商品小计
function updateProductTotal(index) {
    const product = document.querySelectorAll('.product')[index];
    const numInput = product.querySelector('input[name="num"]');
    const price = parseFloat(product.querySelector('.pic').innerText);
    const total = price * parseInt(numInput.value);
    product.querySelector('.rmb').innerText = total.toFixed(2);
    total();
}

// 计算总金额
function total() {
    let sum = 0;
    const checkboxes = document.querySelectorAll('.checkbox:checked');
    checkboxes.forEach(checkbox => {
        const product = checkbox.closest('.product');
        const rmb = product.querySelector('.rmb');
        sum += parseFloat(rmb.innerText);
    });
    totalSpan.innerText = sum.toFixed(2);
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    const cartItems = JSON.parse(localStorage.getItem('cartItems')) || [];
    cartItems.forEach(productInfo => {
        addToCart(productInfo);
    });
    updateCartStatus();
    bindCartEvents();

    const buyBtn = document.getElementById('buyBtn');
    buyBtn.addEventListener('click', function() {
        const checkedProducts = [];
        const checkboxes = document.querySelectorAll('.checkbox:checked');
        checkboxes.forEach(checkbox => {
            const product = checkbox.closest('.product');
            const imgSrc = product.querySelector('img').src;
            const name = product.querySelector('.info p').innerText;
            const price = parseFloat(product.querySelector('.pic').innerText);
            const quantity = parseInt(product.querySelector('input[name="num"]').value);
            checkedProducts.push({
                imgSrc,
                name,
                price,
                quantity
            });
        });

        if (checkedProducts.length > 0) {
            // 获取已有订单
            const existingOrders = JSON.parse(localStorage.getItem('orders')) || [];
            // 添加新订单
            const newOrders = existingOrders.concat(checkedProducts);
            localStorage.setItem('orders', JSON.stringify(newOrders));
            
            alert('购买成功');
            
            // 移除已购买的商品
            checkboxes.forEach(checkbox => {
                const product = checkbox.closest('.product');
                product.remove();
            });
            
            // 更新购物车状态和总金额
            updateCartStatus();
            total();
            
            // 更新本地存储的购物车商品
            const remainingProducts = [];
            const allProducts = document.querySelectorAll('.product');
            allProducts.forEach(product => {
                const imgSrc = product.querySelector('img').src;
                const name = product.querySelector('.info p').innerText;
                const price = parseFloat(product.querySelector('.pic').innerText);
                const quantity = parseInt(product.querySelector('input[name="num"]').value);
                remainingProducts.push({
                    imgSrc,
                    name,
                    price,
                    quantity
                });
            });
            localStorage.setItem('cartItems', JSON.stringify(remainingProducts));
        }
    });
});